from flask import jsonify
from common.common import Response
import hashlib
import os
from common.logger_config import setup_logger

logger = setup_logger(__name__)


class ImageUploadResponse:
    def __init__(self, indexName, imageId, tags, faces, md5):
        self.indexName = indexName
        self.imageId = imageId
        self.tags = tags or []
        self.faces = faces or []
        self.md5 = md5 or []

    # 将对象转换为字典格式，以便返回 JSON 响应
    def to_dict(self):
        return {
            "indexName": self.indexName,
            "imageId": self.imageId,
            "tags": self.tags,
            "faces": self.faces,
            "md5": self.md5,
        }


class ImageSearchInnerResponse:
    def __init__(self, imageId, score):
        self.imageId = imageId
        self.score = score

    # 将对象转换为字典格式，以便返回 JSON 响应
    def to_dict(self):
        return {
            "imageId": self.imageId,
            "score": self.score
        }


class ImageSearchResponse:
    def __init__(self, images: list[ImageSearchInnerResponse], total):
        self.images = images
        self.total = total

    # 将对象转换为字典格式，以便返回 JSON 响应
    def to_dict(self):
        return {
            "images": [image.to_dict() for image in self.images],
            "total": self.total
        }


def calculate_md5(response):
    md5_hash = hashlib.md5()

    # 逐块读取文件内容并更新哈希对象
    for chunk in response.iter_content(chunk_size=8192):  # 按块读取文件，避免内存占用过大
        md5_hash.update(chunk)

    return md5_hash.hexdigest()


# 最大文件大小设置（5MB）
MAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB


# 允许的文件扩展名
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def check_image_param(save_file_path):
    with open(save_file_path, 'rb') as file:
        file_data = file.read()

    if not file_data:
        return jsonify(Response(20001, "param failure", None, "file is blank").to_dict()), 200

    # 获取文件名称和后缀
    file_name = os.path.basename(save_file_path)  # 'melon.jpg'
    # file_name_without_extension, file_extension = os.path.splitext(file_name)  # ('melon', '.jpg')

    if file_name == '':
        return jsonify(Response(20001, "param failure", None, "file name is blank").to_dict()), 200

    file_length = len(file_data)
    if file_length > MAX_FILE_SIZE:
        return jsonify(Response(20001, "param failure", None, "file size exceeds 5MB").to_dict()), 200

    if not allowed_file(file_name):
        return jsonify(Response(20001, "param failure", None, "file type is not allowed").to_dict()), 200

    return jsonify(Response(200, "", None, "").to_dict()), 200


def check_image_id_param(image_ids):  # imageId查询校验
    if image_ids and isinstance(image_ids, list):
        if len(image_ids) > 500:
            return jsonify(Response(20001, "param failure", None, "params length exceeds 500").to_dict()), 200
        for item in image_ids:
            if not isinstance(item, str):
                return jsonify(Response(20001, "param failure", None, "imageId is not str.").to_dict()), 200
            if not item.strip():
                return jsonify(Response(20001, "param failure", None, "index name is blank").to_dict()), 200
        return jsonify(Response(200, "", None, "").to_dict()), 200
    else:
        return jsonify(Response(20001, "param failure", None, "imageId param is blank").to_dict()), 200
